package net.wanho.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.SneakyThrows;
import net.wanho.properties.AlipayProperties;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-10-23 10:24
 * Description：<描述>
 */
@RestController
@RequestMapping("/alipay")
@CrossOrigin
public class AlipayController {

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private AlipayTradePagePayRequest payRequest;

    @Resource
    private AlipayProperties alipayProperties;

    @SneakyThrows
    @PostMapping("/pay")
    public void pay(String orderNo, String subject, Double totalAmount, HttpServletResponse response){
        // 封装业务参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        bizContent.put("subject", subject);
        bizContent.put("total_amount", totalAmount);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        bizContent.put("timeout-express", "30m"); // 超时时间，30分钟

        payRequest.setBizContent(bizContent.toString());

        // 向支付宝发起支付请求
        String result = alipayClient.pageExecute(payRequest).getBody(); // 这里的result是一个html页面

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(result);
    }

    @SneakyThrows
    @PostMapping("/notify")
    public String notifyUrl(@RequestParam Map<String,String> params){
        System.out.println(params);

        /**
         * 进行验签操作，防止签名被篡改
         */
        boolean flag = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), "utf-8", alipayProperties.getSignType());
        if(!flag){
            System.out.println("验签失败");
            return "fail";
        }

        /**
         * 判断返回的订单号、订单金额是否正确，防止数据被篡改
         */
        String orderNo = params.get("out_trade_no");
        String totalAmount = params.get("total_amount");


        /**
         * 判断支付宝返回的状态码是否正确
         */
        String tradeStatus = params.get("trade_status");
        if(!"TRADE_SUCCESS".equals(tradeStatus)){
            System.out.println("支付失败");
            return "fail";
        }

        /**
         * 更新相应的订单状态，将订单状态改为已支付
         */
        // orderService.updateOrderStatus();

        return "success";
    }

}
